package com.ucpaas.dmp.web.controller.common;


import com.ucpaas.dmp.web.config.TemplatePathConfig;
import com.ucpaas.paas.web.controller.BaseController;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

@Controller
@RequestMapping({"/download/template"})
public class DownloadTemplateCommon extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private TemplatePathConfig templatePathConfig;


    @RequestMapping(value = "/mobile-example")
    public ResponseEntity<byte[]> download(HttpServletRequest request) throws FileNotFoundException {
        String path = ResourceUtils.getURL("classpath:").getPath() + templatePathConfig.getPhoneXlsx() ;
        return example(path, "手机号导入模板.xlsx");
    }

    @RequestMapping(value = "/mobile-example-csv")
    public ResponseEntity<byte[]> downloadCSV(HttpServletRequest request) throws FileNotFoundException {
        String path = ResourceUtils.getURL("classpath:").getPath() + templatePathConfig.getPhoneCsv();
        return example(path, "手机号导入模板.csv");
    }

    @RequestMapping(value = "/mobile-example-txt")
    public ResponseEntity<byte[]> downloadTXT(HttpServletRequest request) throws FileNotFoundException {
        String path = ResourceUtils.getURL("classpath:").getPath() + templatePathConfig.getPhoneTxt();
        return example(path, "手机号导入模板.txt");
    }


    public ResponseEntity<byte[]> example(String path, String fileName) {
        File downloadFile = new File(path);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("utf8"), "ISO-8859-1"));
        } catch (UnsupportedEncodingException e) {
            headers.setContentDispositionFormData("attachment", fileName);
        }
        try {
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(downloadFile), headers, HttpStatus.CREATED);
        } catch (IOException e) {
            logger.error("DownloadTemplateCommon.example()下载模板异常:{},fileName={}", e.getMessage(), fileName, e);
            return null;
        }
    }

}
